package com.example.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.Result;
import com.example.reggie.domain.User;
import com.example.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RequestMapping("/user")
@Slf4j
@RestController
public class UserController {

    @Autowired
    UserService userService;

    // 用户登录
    @PostMapping("/login")
    Result<User> userLogin(HttpServletRequest request, @RequestBody Map map){
        log.info("map: {}",map.toString());
        String phone = (String) map.get("phone");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if (user!=null){
            request.getSession().setAttribute("user",user.getId());
            return Result.success(user);
        }
        else {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            user.setName(phone);
            userService.save(user);
            request.getSession().setAttribute("user",user.getId());
            return Result.success(user);
        }
    }

    // 退出登录
    @PostMapping("/loginout")
    Result<String> userLogout(HttpServletRequest  request){
        request.getSession().removeAttribute("user");
        return Result.success("退出成功");
    }
}
